package cc.catface.base.net.core;

import android.util.Log;

import java.util.concurrent.TimeUnit;

import cc.catface.base.net.Api;
import cc.catface.base.net.core.cookie.AddCookiesInterceptor;
import cc.catface.base.net.core.cookie.ReceivedCookiesInterceptor;
import okhttp3.OkHttpClient;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;

/** 创建retrofit实例 */
public class RetrofitHelper {

    /** 打印日志 */
    private static final String LOG_TAG = "retrofit-request";

    public static void d(String msg) {
        Log.d(LOG_TAG, msg);
    }

    /** 单例 */
    private static class Holder {
        static Api instance = new RetrofitHelper().getRetrofit();
    }

    public static Api getApi() {
        return Holder.instance;
    }

    public Api getRetrofit() {
        return initRetrofit(initOkHttp()).create(Api.class);
    }

    private Retrofit initRetrofit(OkHttpClient client) {
        return new Retrofit.Builder().client(client)
                .baseUrl("http://172.17.25.156:8080/")//可能同时请求多个ip所以每个请求手动传入完整的url
                .addCallAdapterFactory(RxJava2CallAdapterFactory.create())//支持rx
                .addConverterFactory(GsonConverterFactory.create())//支持gson解析
                .build();
    }

    private OkHttpClient initOkHttp() {
        return new OkHttpClient().newBuilder()
                .readTimeout(10, TimeUnit.SECONDS)
                .connectTimeout(10, TimeUnit.SECONDS)
                .writeTimeout(10, TimeUnit.SECONDS)
                .addInterceptor(new ReceivedCookiesInterceptor()).addInterceptor(new AddCookiesInterceptor())//cookie
                .addInterceptor(new BizInterceptor())
                .retryOnConnectionFailure(true)
                //.protocols(Collections.unmodifiableList(Arrays.asList(Protocol.HTTP_1_1, Protocol.HTTP_2)))//支持协议
                .build();
    }
}

